package models

import (
	db "webGin/database"
	"log"
)

type User struct {
	Id       int64  `json:"id" form:"id"`
	Uuid     string `json:"uuid" form:"uuid"`
	Account  string `json:"account" form:"account"`
	Password string `json:"password" form:"password"`
	Email    string `json:"email"`
	Nickname string `json:"nickname"`
	Mobile   string `json:"mobile"`
	Avatar   string `json:"avatar"`
	Sex      string `json:"sex"`
}

func GetLists() (users []User, err error) {
	users = make([]User, 0)
	rows, err := db.SqlDB.Query("SELECT id,uuid,account,email,nickname,mobile,avatar,sex FROM users")
	defer rows.Close()
	if err != nil {
		log.Println(err.Error())
		return
	}
	for rows.Next() {
		var user User
		rows.Scan(&user.Id, &user.Uuid, &user.Account, &user.Email, &user.Nickname, &user.Mobile, &user.Avatar, &user.Sex)
		users = append(users, user)
	}
	if err = rows.Err(); err != nil {
		log.Println(err.Error())
		return
	}
	return
}

func (u *User) Add() (id int64, err error) {
	rs, err := db.SqlDB.Exec("INSERT INTO users(uuid,account,password)VALUES(?,?,?)", u.Uuid, u.Account, u.Password)
	if err != nil {
		log.Println(err.Error())
		return
	}
	id, err = rs.LastInsertId()
	return
}

func (u *User) Info(req User) (user User, err error) {
	err = db.SqlDB.QueryRow("SELECT id,uuid,account,password,email,nickname,mobile,avatar,sex FROM users WHERE account = ?",
		req.Account).Scan(&user.Id,&user.Uuid,&user.Account,&user.Password,&user.Email,&user.Nickname,&user.Mobile,&user.Avatar,&user.Sex)
	if err != nil {
		log.Println(err.Error())
		return
	}
	return
}
